<template>
  <div class="data-v-loading2" :style="hostSty">
    <div class="text">
      <canvas width="20" height="20" ref="canvas"></canvas>
      <span style="margin: 0 5px">{{ percent }}</span>
      正在加载中<span>{{ dot }}</span>
    </div>
    <div class="bar-outer">
      <div class="bar-inner" :style="sty"></div>
    </div>
  </div>
</template>

<script>
import Color from 'color-js';
import Circle from "./Circle";
export default {
  name: "data-v-loading2",
  props: ["percentage", "color"],
  computed: {
    percent() {
      return (this.percentage * 100).toFixed(2) + "%";
    },
    sty() {
      return {
        width: this.percent
      };
    },
    hostSty(){
      let c = Color(this.color);
      return {
        '--color': this.color,
        '--color-background': c.darkenByAmount(0.25),
        '--color-text': c.lightenByAmount(0.2),
      };
      
    }
  },
  data() {
    return {
      dot: ""
    };
  },
  created() {
    this.timer = setInterval(() => {
      this.dot += ".";
      if (this.dot.length > 6) {
        this.dot = "";
      }
    }, 500);
  },

  mounted() {
    const canvas = this.$refs.canvas;
    const ctx = canvas.getContext("2d");

    let centerX = canvas.width / 2;
    let centerY = canvas.height / 2;

    let gradnent = ctx.createLinearGradient(0, 0, 20, 15);
    gradnent.addColorStop(0, this.color);
    gradnent.addColorStop(1, "transparent");

    let circle = new Circle(8, gradnent);
    circle.x = centerX;
    circle.y = centerY;
    circle.startAngle = 0;
    circle.endAngle = 270;

    function drawFrame() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      // 让circle1旋转
      circle.rotation += 1.5;
      if (circle.rotation > 360) {
        circle.rotation = 0;
      }

      circle.draw(ctx);
      requestAnimationFrame(drawFrame);
    }

    drawFrame();
  },

  destroyed() {
    clearInterval(this.timer);
  }
};
</script>

<style lang="less">

.data-v-loading2 {
  display: inline-block;
  width: 360px;

  height: 56px;
  padding: 10px; 
  margin: 10px;
  background: var(--color-background);

  border-left: 4px solid var(--color);
  border-right: 4px solid  var(--color);
  border-top: 1px solid var(--color);
  border-bottom: 1px solid var(--color);

  .text {
    color: var(--color-text);
    display: flex;
    align-items: center;
  }

  .bar-outer {
    margin: auto;
    margin-top: 10px;
    height: 5px;
    background: #000;
    .bar-inner {
      background: var(--color);
      height: 100%;
      width: 50%;
      box-shadow: 1px 0 3px var(--color);
      transition: width 0.25s;
    }
  }
}
</style>
